package com.examinantsdk.base.http.converter;

import android.os.Bundle;

import com.examinantsdk.base.http.HttpStatus;
import com.examinantsdk.bean.MobileBean;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Create by Carson on 2021/3/16.
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, Object> {

    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public Object convert(ResponseBody value) throws IOException {
        String res = value.string();
        try {
            HttpStatus httpStatus = new Gson().fromJson(res, HttpStatus.class);
            if (httpStatus.getStatus() == 0) {
                BaseResponse response = (BaseResponse) adapter.fromJson(res);
                return response.getData();
            } else {
                if (httpStatus.getStatus() == 2 || (httpStatus.getStatus() == 1 && httpStatus.getCode() == 4440)) {
                    throw new IOException("token_invalid");
                } else if (httpStatus.getCode() == 4450) {
//                    BaseResponse<MobileBean> mobileBean = new Gson().fromJson(res, new TypeToken<BaseResponse<MobileBean>>() {}.getType());
//                    Bundle bundle = new Bundle();
//                    bundle.putString("phone", mobileBean.getData().getMobile());
//                    ExtKt.go(MyApplication.getInst(), RecoverAccountDialog.class, bundle);
                    throw new IOException("");
                } else
                    throw new IOException(httpStatus.getMsg());
            }

//            BaseResponse response = (BaseResponse) adapter.fromJson(res);
//            if (response.getStatus() == 0) {
//                return response.getData();
//            }
//            else {
////                throw new ServerResponseException("", response.getStatus(), response.getMsg());
//                if (response.getStatus() == 2 || (response.getStatus() == 1 && response.getCode() == 4440)) {
//                    throw new IOException("token_invalid");
//                }
//
//                throw new IOException(response.getMsg());
//            }
        } finally {
            value.close();
        }
    }
}
